//
//  JBPlaceholderTextView.swift
//  sinaBlog
//
//  Created by jobo on 15/11/8.
//  Copyright © 2015年 jobo. All rights reserved.
//

import UIKit

class JBPlaceholderTextView: UITextView {

    //占位文本属性,当外界给这个文本赋值的时候,把这个值付给labeltext,
    var placeholder : String?
    {
        didSet
        {
            placeceholderLabel.text = placeholder
            
            placeceholderLabel.font = font
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        prepareForUI()
        // 使用通知
        // object: 表示通知的发送者.
        // object = nil 表示任何人发送的 UITextViewTextDidChangeNotification 都能接受到
        // 指定 object, 表示只有 object 发送出来的 UITextViewTextDidChangeNotification 才能接受到
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange:", name: UITextViewTextDidChangeNotification, object: self)
    
    }
    
    //通知
    deinit {
        // 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func textViewDidChange(notification: NSNotification) {
        // textView没有文本的时候显示占位文本
        placeceholderLabel.hidden = hasText()
    }
    
    //准备UI
    func prepareForUI()
    {
        //添加子控制器
        addSubview(placeceholderLabel)
        //设置约束
        placeceholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        self.addConstraint(NSLayoutConstraint(item: placeceholderLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))
        self.addConstraint(NSLayoutConstraint(item: placeceholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        
    }
    
    
    lazy var placeceholderLabel : UILabel =
    {
        //设置占位文本
        let cpLabel = UILabel()
        
        cpLabel.textColor = UIColor.lightGrayColor()
        
        cpLabel.sizeToFit()
        
        return cpLabel
    }()
    
    
}
